import { useMemo, Ref } from 'react';

export type IRefs<T> = Ref<T> | null | undefined;

export function setRef<T>(
    ref: React.MutableRefObject<T | null> | ((instance: T | null) => void) | null | undefined,
    value: T | null
): void {
    if (typeof ref === 'function') {
        ref(value);
    } else if (ref) {
        ref.current = value;
    }
}
export function useForkRef<Instance>(...refs: IRefs<Instance>[]) {
    return useMemo(() => {
        if (refs.every((ref) => !ref)) {
            return null;
        }
        return (refValue: Instance | null) => {
            for (const ref of refs) {
                if (ref) {
                    setRef(ref, refValue);
                }
            }
        };
    }, [refs]);
}
